import requests
from app.extensions import db
from app.models import DetectionEvent
from app.config import Config
import os


def update_street_names():
    """调用高德API，为没有街道名的检测事件补全街道名"""
    # 获取所有未解析街道名的事件
    events = DetectionEvent.query.filter(DetectionEvent.street_name.is_(None)).all()
    amap_key = os.getenv('AMAP_API_KEY')  # 从环境变量获取高德API密钥

    if not amap_key:
        print("警告：未配置高德API密钥，无法解析街道名")
        return

    for event in events:
        if event.lat and event.lng:  # 确保经纬度存在
            # 调用高德逆地理编码API
            url = f"https://restapi.amap.com/v3/geocode/regeo?key={amap_key}&location={event.lng},{event.lat}"
            try:
                response = requests.get(url).json()
                if response.get('status') == '1':  # 接口调用成功
                    # 提取街道名（乡镇级）
                    street = response['regeocode']['addressComponent'].get('township', '')
                    if not street:  # 若乡镇为空，取街道级
                        street = response['regeocode']['addressComponent'].get('street', '')
                    event.street_name = street
                    print(f"更新街道名：{street}（事件ID：{event.id}）")
            except Exception as e:
                print(f"解析街道名失败：{str(e)}")

    db.session.commit()  # 批量提交更新